package com.epam.player.desktop.logic;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import javax.swing.JProgressBar;

import com.epam.player.vkapi.model.Song;

public class SaverMP3 {

	private int length;

	public boolean saveMp3(String name, Song song, JProgressBar jProgressBar) {
		URL url = song.getUrl();
		InputStream inputStream = null;
		try {
			length = url.openConnection().getContentLength();
			inputStream = url.openStream();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		File f = new File(name);
		OutputStream out = null;
		try {
			out = new FileOutputStream(f);
			byte buf[] = new byte[1024];
			int len;
			int sum = 0;
			while ((len = inputStream.read(buf)) > 0) {
				sum = sum + len;
				int persentDownload = (sum * 100) / length;
				jProgressBar.setValue(persentDownload);
				out.write(buf, 0, len);
			}
		} catch (IOException e) {
			return false;
		}

		try {
			out.close();
			inputStream.close();
		} catch (IOException e) {
			return false;
		}
		return true;
	}
}
